package com.java.simple.study.juc.p7;

import com.java.simple.study.tool.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author zhoujunlin
 * @date 2022年08月06日 20:55
 * @desc
 */
@Slf4j(topic = "c.TestTimer")
public class TestTimer {

    public static void main(String[] args) {
        //testTimer();
        //testSchedulePool();
        //testScheduleFixRate1();
        //testScheduleFixRate2();

        log.debug("start...");
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);
        scheduledThreadPool.scheduleWithFixedDelay(() -> {
            log.debug("running...");
            Sleeper.sleep(2);
        }, 1, 1, TimeUnit.SECONDS);

    }

    private static void testScheduleFixRate2() {
        log.debug("start...");
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);
        scheduledThreadPool.scheduleAtFixedRate(() -> {
            log.debug("running...");
            Sleeper.sleep(2);
        }, 1, 1, TimeUnit.SECONDS);
    }

    private static void testScheduleFixRate1() {
        log.debug("start...");
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);
        scheduledThreadPool.scheduleAtFixedRate(() -> {
            log.debug("running...");
        }, 1, 1, TimeUnit.SECONDS);
    }

    private static void testSchedulePool() {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);
        // 添加两个任务  让它们都在1s后执行
        scheduledThreadPool.schedule(() -> {
            log.debug("task1");
            Sleeper.sleep(2);
        }, 1000, TimeUnit.MILLISECONDS);

        scheduledThreadPool.schedule(() -> {
            log.debug("task2");
        }, 1000, TimeUnit.MILLISECONDS);
    }

    private static void testTimer() {
        Timer timer = new Timer();
        TimerTask task1 = new TimerTask() {
            @Override
            public void run() {
                log.debug("task1");
                Sleeper.sleep(2);
            }
        };

        TimerTask task2 = new TimerTask() {
            @Override
            public void run() {
                log.debug("task2");
            }
        };
        log.debug("start...");
        // 使用 timer 添加两个任务，希望它们都在 1s 后执行
        // 但由于 timer 内只有一个线程来顺序执行队列中的任务，因此『任务1』的延时，影响了『任务2』的执行
        timer.schedule(task1, 1000);
        timer.schedule(task2, 1000);
    }


}
